<?php
/**
 * Created by PhpStorm.
 * User: Digvijay
 * Date: 8/9/14
 * Time: 9:47 AM
 */
class Inventory extends MY_Controller {
    function index() {
        $data = array("pageTitle" => "Dashbord");
        $this->load->view("admin/dashbord", $data);
    }

    function stock() {
        $categories = $this->findAll("Category");
        $locations = $this->findAll("Branch");
        $data = array("pageTitle" => "Stock Management", "categories" => $categories, "locations" => $locations);
        $this->load->view("admin/inventory-stock", $data);
    }

    function category() {
        $data = array("pageTitle" => "Category Management");
        $this->load->view("admin/inventory-category", $data);
    }

    function addEditProduct() {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            $id = strip_tags(trim($this->input->post("product-id")));
            $name = strip_tags(trim($this->input->post("product-name")));
            $details = (trim($this->input->post("product-details")));
            $categoryId = strip_tags(trim($this->input->post("product-category")));
            $price = strip_tags(trim($this->input->post("product-price")));
            $discount = strip_tags(trim($this->input->post("product-discount")));
            $productImages = $this->input->post("product-img");
            $productHeaderImg = strip_tags($this->input->post("product-header-img"));

            $product = null;
            if ($id != null && $id != "") {
                $product = $this->findById("Product", $id);
                $product->clearImages();
            } else {
                if ($this->findByName($name, "Product") != null) {
                    throw new RuntimeException("Product with name " . $name . " already exist.");
                }
                $product = new Product();
                $product->setDateCreate(new DateTime());

                //This values cannot be edited for this request. Only Created once, i.e while creating new product.
                $locations = $this->findAll("Branch");
                foreach ($locations as $location) {
                    $stock = new Stock();
                    $stock->setActualStock(0);
                    $stock->setTotalStock(0);
                    $stock->setLocation($location);
                    $product->addStock($stock);
                }
            }
            $product->setName($name);
            $product->setDetails($details);
            $product->setCategory($this->findById("Category", $categoryId));
            $product->setPrice($price);
            $product->setDiscount($discount);
            $product->setActive(true);

            foreach ($productImages as $img) {
                $image = new Image();
                $image->setName(strip_tags($img));
                if ($productHeaderImg == strip_tags($img)) {
                    $image->setIsCover(true);
                }
                $product->addImage($image);
            }
            $this->save($product);
            $product->setImages($product->getImages()->toArray());
            $response->setData($product);
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
            log_message("error", $e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    function getProduct($id = null) {
       if (!$this->input->is_ajax_request()) {
            show_404();
            return;
       }
        $response = new Response();
        try {
            if ($id == null) {
                $products = $this->findAllProduct();
                foreach ($products as $product) {
                    $product->setStock($product->getStock()->toArray());
                    $product->setImages($product->getImages()->toArray());
                }
                $response->setData($products);
            } else if ($id != "") {
                $product = $this->findById("Product", $id);
                $product->setStock($product->getStock()->toArray());
                $product->setImages($product->getImages()->toArray());
                $response->setData($product);
            } else {
                throw new Exception("Invalid Product Id " . $id);
            }
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    function getCategory($id = null) {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            if ($id == null) {
                $categories = $this->findAll("Category");
                $response->setData($categories);
            } else if ($id != "") {
                $category = $this->findById("Category", $id);
                $response->setData($category);
            } else {
                throw new Exception("Invalid Category Id " . $id);
            }
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response);
    }

    function addEditTopCategory() {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            $id = trim($this->input->post("top-category-id"));
            $name = trim($this->input->post("category-name"));
            $category = new Category();
            $category->setDateCreate(new DateTime());
            if($id != "" && $id != null){
                $category = $this->findById("Category", $id);
            }
            $category->setName($name);
            $this->save($category);
            $response->setData($category);

            $categories = $this->findAll("Category");
            $response->setData($categories);
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response);
    }

    function addEditCategory() {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            $id = trim($this->input->post("category-id"));
            $name = trim($this->input->post("category-name"));
            $parentCategory = trim($this->input->post("parent-category"));
            $category = new Category();
            $category->setDateCreate(new DateTime());
            if ($id != "" && $id != null) {
                $category = $this->findById("Category", $id);
            } else {
                if ($this->findByName($name, "Category")) {
                    throw new RuntimeException("Category already Exist.");
                }
            }
            $category->setName($name);
            $category->setParent($this->findById("Category", $parentCategory));
            $this->save($category);
            $categories = $this->findAll("Category");
            $response->setData($categories);
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response);
    }

    function deleteCategory($id = null) {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            if ($id != null && $id != "") {
                $category = $this->findById("Category", $id);

                if($category->getParent() != null){
                    $result = $this->getProductByCategoryId($category);
                    if ($result != null) {
                        throw new RuntimeException("Cannot Delete Category, Product with this category exist.");
                    }
                }else{
                    $categories = $this->getAllSubCategories($category);
                    foreach($categories as $sub){
                        $result = $this->getProductByCategoryId($sub);
                        if ($result != null) {
                            throw new RuntimeException("Cannot Delete Category, Product with category ".$sub->getName()." exist.");
                        }
                    }
                }
                $this->delete($category);
                $categories = $this->findAll("Category");
                $response->setData($categories);
            } else {
                throw new Exception("Invalid Category Id " . $id);
            }
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response);
    }


    function updateStock() {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            $id = strip_tags(trim($this->input->post("p-id")));
            $locationId = strip_tags(trim($this->input->post("p-location")));
            $newStock = strip_tags(trim($this->input->post("p-new-stock")));
            $price = strip_tags(trim($this->input->post("p-price")));
            $discount = strip_tags(trim($this->input->post("p-discount")));

            if ($newStock == null || $newStock == "") {
                $newStock = 0;
            }
            if ($price == null || $price == "") {
                throw new RuntimeException("Please enter price.");
            }
            if ($discount == null || $discount == "") {
                $discount = 0;
            }

            $product = $this->findById("Product", $id);
            if ($product != null) {
                $stocks = $product->getStock();
                foreach ($stocks as $stock) {
                    if ($stock->getLocation()->getId() == $locationId) {
                        if ($newStock > 0) {
                            $stock->setActualStock($stock->getActualStock() + $newStock);
                            $stock->setTotalStock($stock->getTotalStock() + $newStock);
                        }
                    }
                }
                if ($price >= 0) {
                    $product->setPrice($price);
                }
                if ($discount >= 0) {
                    $product->setDiscount($discount);
                }
                $this->save($product);

                $product->setImages($product->getImages()->toArray());
                $product->setStock($product->getStock()->toArray());
                $response->setData($product);
            } else {
                throw new RuntimeException("Product Not Found For Id :" . $id);
            }
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response);
    }

    function getStock($id = null, $prodId = null) {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            if ($id != null && $prodId != null) {
                $product = $this->findById("Product", $prodId);
                $stock = null;
                foreach ($product->getStock() as $stk) {
                    if ($stk->getLocation()->getId() == $id) {
                        $stock = $stk;
                        break;
                    }
                }
                $response->setData($stock);
            }
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response);
    }

    function findProductByName() {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $productName = strip_tags(trim($this->input->post("product-name")));
        $response = new Response();
        try {
            $query = $this->em->createQuery("SELECT o FROM Product o WHERE o.name LIKE :name");
            $query->setParameter("name", "%" . $productName . "%");
            $products = $query->getResult();
            if ($products == null || count($products) == 0) {
                throw new RuntimeException("No Product was found by name :" . $productName);
            }
            foreach ($products as $product) {
                $product->setImages($product->getImages()->toArray());
                $product->setStock($product->getStock()->toArray());
            }
            $response->setData($products);
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response);
    }

    public function findProductByCategory($categoryId = null) {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            $products = null;
            if ($categoryId == null) {
                $products = $this->findAllProduct();
            } else {
                $category = $this->findById("Category", $categoryId);
                $products = $this->getProductByCategoryId($category);
            }
            foreach ($products as $product) {
                $product->setImages($product->getImages()->toArray());
                $product->setStock($product->getStock()->toArray());
            }
            $response->setData($products);
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    public function deleteproduct($id = null){
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            if($id == null || $id == ""){
                throw new RuntimeException("Invalid Request");
            }
            $product = $this->findById("Product", $id);
            $isSafeToDelete = true;
            foreach ($product->getStock() as $stk) {
                if($stk->getTotalStock() != 0){
                    $isSafeToDelete = false;
                }
            }
            if($isSafeToDelete){
                $product->setActive(false);
            }else{
                throw new RuntimeException("Cannot Delete, Product is having stock.");
            }
            $this->save($product);
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }
} 